#######################################################
# Example of FDDEVS network model for a two-slot toaster 
# Author: moonho.hwang@gmail.com
#   Date: Oct.19.2011
#######################################################

from XSY.DEVS.CoupledDEVS import *
from ToasterFD import * 

def make_input_event(md, JSONarg=None):
   ''' a callback function for injection'''
   ipn = raw_input('input port name ?push1 or ?push2>')
   if ipn in md.IP:
      ip = md.IP[ipn]
      return PortValue(ip)
   else:
      return None # inject None into timer 

def makeModel(name, tA, tB):
   md1 = Toaster("t1", tA) 
   md2 = Toaster("t2", tB) 
   cm = CoupledDEVS(name, None)
   cm.addComponents(md1, md2)
   cm.addInputPorts("?push1", "?push2")
   cm.addOutputPorts("!pop1", "!pop2")

   cm.addCouple(cm.IP["?push1"], md1.IP["?push"])
   cm.addCouple(cm.IP["?push2"], md2.IP["?push"])
   cm.addCouple(md1.OP["!pop"], cm.OP["!pop1"])
   cm.addCouple(md2.OP["!pop"], cm.OP["!pop2"])
   return cm

def runSimulation(md):
   engine = SimEngine(md1, make_input_event)

   #---- setting StepByStep and DES simulation only ----
   engine.StepByStep = True
   engine.sfactor = float('inf')
   #----------------------------------------------------
   engine.runInteractiveMenu()

def runVerification(md):
   X = []
   X.append(PortValue(md.IP['?push1']))
   #X.append(PortValue(md.IP['?repair1']))
   X.append(PortValue(md.IP['?push2']))
   #X.append(PortValue(md.IP['?repair2']))
   VE = VeriEngine(md, X, None, None)
   VE.runtimeInteractiveMenu()


if __name__ == '__main__':
   print 'This example shows a coupled model "system" having two toaster "ts1" and "ts2" '
   print 'which can get started toasting by injection of "?push1" or "?push2", resectively'

   md1 = makeModel("", 20, 40) 

   c = True
   while c:
      s = raw_input('[s]im, [v]eri, e[x]it>')
      if s == 's' or s == 'sim': 
         runSimulation(md1)
      elif s == 'v' or s == 'veri':
         runVerification(md1)
      elif s == 'x' or s == 'exit':
         c = False
      else:
         print('%s is an invalid input!'%s)
      
   print "good bye~!" 
  
